package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;

import javax.validation.constraints.NotNull;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.Alarm;
import com.ruoyi.system.domain.AlarmDetail;
import com.ruoyi.system.domain.ValidationGroups.Select;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/system/alarm")
public class AlarmController extends BaseController {
    @Autowired
    IAlarmService alarmService;

    @Autowired
    IAlarmDetailService alarmDetailService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    ISysDeptService sysDeptService;

    @Autowired
    private IProjectAuthorizeService projectAuthorizeService;

    @Autowired
    private ICustomPermissionService customPermissionService;
    @Autowired
    private ISysUserService sysUserService;

    @PreAuthorize("@ss.hasPermi('system:alarm:list')")
    @GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
    public Object index(@Validated(Select.class) Alarm alarm) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        boolean commonRole = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (alarm.getProjectId() != null && !commonRole){
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),alarm.getProjectId());
        }
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("project_id", alarm.getProjectId());
        queryVo.filters.put("project_name", alarm.getProjectName());
        queryVo.filters.put("rule_id", alarm.getRuleId());
        queryVo.filters.put("rule_name", alarm.getRuleName());
        queryVo.filters.put("severity", alarm.getSeverity());
        queryVo.filters.put("description", alarm.getDescription());
        queryVo.filters.put("trigger_logic", alarm.getTriggerLogic());
        queryVo.filters.put("start", alarm.getStart());
        queryVo.filters.put("end", alarm.getEnd());
        queryVo.filters.put("recovered", alarm.getRecovered());
        queryVo.filters.put("comment", alarm.getComment());
        queryVo.filters.put("handled_by", alarm.getHandledBy());
        queryVo.filters.put("handled", alarm.getHandled());
        queryVo.filters.put("company_id", companyId);
        queryVo.filters.put("sn", alarm.getSn());
        boolean flag = sysDeptService.checkIsCustomer(loginUser.getUser().getDeptId());
        if (flag){
            Long customerId = sysDeptService.getCustomerId(loginUser.getUser().getDeptId());
            queryVo.filters.put("dept_id",customerId);
        }
        if (!commonRole){
            String sql = customPermissionService.getProjectAuthorizePermission("a", "project_id", loginUser.getUser());
            queryVo.setCustomPermissionSql(sql);
        }
        startPage();
        List<Alarm> alarms = alarmService.index(queryVo);
        return getDataTable(alarms);
    }

    @PreAuthorize("@ss.hasPermi('system:alarm:list')")
    @GetMapping(value = "/detail_list", produces = "application/json;charset=UTF-8")
    public Object indexDetail(@RequestParam(name = "deviceId", required = false) Integer deviceId) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("device_id", deviceId);
        queryVo.filters.put("company_id", companyId);
        String sql = customPermissionService.getProjectAuthorizePermission("d", "project_id", loginUser.getUser());
        queryVo.setCustomPermissionSql(sql);
        startPage();
        List<AlarmDetail> alarmDetails = alarmDetailService.index(queryVo);
        return getDataTable(alarmDetails);
    }

    @PreAuthorize("@ss.hasPermi('system:alarm:query')")
    @GetMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieve(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        Alarm alarm = alarmService.retrieve(queryVo);
        if (alarm == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        return AjaxResult.success(alarm);
    }

    @PreAuthorize("@ss.hasPermi('system:alarm:handle')")
    @Log(title = "报警", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/handle", produces = "application/json;charset=UTF-8")
    public AjaxResult handle(@RequestBody @Validated(Update.class) Alarm alarm)
    {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", alarm.getId());
        Alarm target = alarmService.retrieve(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        alarm.setHandledBy(loginUser.getUser().getNickName());
        alarm.setHandledAt(new Date());
        if (alarmService.update(alarm)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }
}
